package cc.grapevine.vps;

import java.util.ArrayList;
import java.util.HashMap;
import cc.grapevine.vps.http.HttpManager;
import cc.grapevine.vps.http.HttpRequestVps;
import cc.grapevine.vps.http.URLManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ListVpsActivity extends Activity implements OnItemClickListener
{
	private HttpManager m_httpManager;
	private MessageReciver m_messageReciver;
	private ProgressDialog m_pdgLoading;
	private ListView m_listView;
	private HashMap<String, VpsData> m_Data;
	private UserManager m_Manager;
	private ListAdapterSelf adapter;
	private ArrayList<VpsData> m_listData;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_vps);
		m_listView = (ListView) findViewById(R.id.vps_list);
		m_listView.setOnItemClickListener(this);
		m_Manager = UserManager.getIntence();
		m_Data = m_Manager.getDataHashMap();
		init();
		m_pdgLoading = new ProgressDialog(this);
		m_pdgLoading.setCancelable(false);
		m_pdgLoading.setTitle(R.string.tip_title);
		m_pdgLoading.setMessage(getString(R.string.tip_message));
		m_pdgLoading.show();
		adapter = new ListAdapterSelf(this);
		reloadData();
		m_listView.setAdapter(adapter);
		startService(new Intent(this, VpsService.class));
	}

	private void init()
	{
		m_httpManager = HttpManager.getInstence();
		m_messageReciver = new MessageReciver();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{

			new AlertDialog.Builder(ListVpsActivity.this).setTitle(R.string.quit_title).setMessage(
					R.string.quit_message).setPositiveButton(R.string.ok, new OnClickListener()
			{

				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					ListVpsActivity.this.finish();
				}
			}).setCancelable(false).setNegativeButton(R.string.cancel, null).create().show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onStart()
	{
		adapter.notifyDataSetChanged();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Action.GET_VPS_LIST);
		filter.addAction(Action.UPDATE_STATUS);
		filter.addAction(Action.NO_LOGIN);
		filter.addAction(Action.HTTP_ERROR);
		filter.addAction(Action.COMMUNICATION_ERROR);
		registerReceiver(m_messageReciver, filter);
		super.onStart();
	}

	@Override
	protected void onStop()
	{
		unregisterReceiver(m_messageReciver);
		super.onStop();
	}

	private void reloadData()
	{
		if (null == m_listData)
		{
			m_listData = new ArrayList<VpsData>();
		}
		m_listData.clear();
		m_listData.addAll(m_Data.values());
	}

	@Override
	protected void onDestroy()
	{
		stopService(new Intent(this, VpsService.class));
		super.onDestroy();
	}

	private class MessageReciver extends BroadcastReceiver
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			String action = intent.getAction();

			if (m_pdgLoading.isShowing())
			{
				m_pdgLoading.dismiss();
			}

			if (Action.UPDATE_STATUS.equals(action) || Action.GET_VPS_LIST.equals(action))
			{
				reloadData();
				adapter.notifyDataSetChanged();
			}
			else if (Action.NO_LOGIN.equals(action))
			{
				showToast(R.string.nologin_error);
				Intent intent2 = new Intent(ListVpsActivity.this, Self2hostLogin.class);
				intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent2);
				ListVpsActivity.this.finish();
			}
			else if (Action.HTTP_ERROR.equals(action))
			{
				showToast(R.string.http_error);

			}
			else if (Action.COMMUNICATION_ERROR.equals(action))
			{
				showToast(R.string.comunication_error);
			}
		}
	}

	private void showToast(int resId)
	{
		Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{

		menu.add(Menu.FIRST, Menu.FIRST, Menu.FIRST, R.string.refresh_list).setIcon(R.drawable.ic_menu_refresh);

		menu.add(Menu.FIRST, Menu.FIRST + 1, Menu.FIRST, R.string.refresh_statues).setIcon(R.drawable.ic_menu_refresh);

		return super.onCreateOptionsMenu(menu);
	}

	private HttpRequestVps m_RequestVpsList = new HttpRequestVps(Action.GET_VPS_LIST, URLManager.LIST_URL);

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		boolean ret = true;

		switch (item.getItemId())
		{
		case Menu.FIRST:
			m_httpManager.addRequest(m_RequestVpsList);
			m_pdgLoading.show();
			break;

		case Menu.FIRST + 1:
			for (String key : m_Data.keySet())
			{
				VpsData data = m_Data.get(key);
				HttpRequestVps requestVps = new HttpRequestVps(Action.UPDATE_STATUS, URLManager.createDecStatus(data
						.getId(), data.getName()));

				requestVps.setId(data.getId());
				requestVps.setName(data.getName());

				if (null != m_httpManager)
				{
					m_httpManager.addRequest(requestVps);
				}
				else
				{
					break;
				}
			}
			if (m_Data.size() > 0)
			{
				m_pdgLoading.show();
			}
			break;
		default:
			ret = super.onOptionsItemSelected(item);
			break;
		}
		return ret;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		Intent intent = new Intent(this, ManagerVps.class);
		VpsData data = m_listData.get(arg2);
		intent.putExtra(Intent.EXTRA_UID, data.getId());
		intent.putExtra(Intent.EXTRA_TEXT, data.getName());
		startActivity(intent);
	}

	private class ListAdapterSelf extends BaseAdapter
	{

		private Context c;

		public ListAdapterSelf(Context c)
		{
			this.c = c;
		}

		@Override
		public int getCount()
		{
			return m_listData.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return m_listData.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			if (null == convertView)
			{
				convertView = LayoutInflater.from(c).inflate(R.layout.simple_list_item_1, null);
			}

			ViewHolder holder = (ViewHolder) convertView.getTag();

			if (null == holder)
			{
				TextView name = (TextView) convertView.findViewById(R.id.text1);
				ImageView statues = (ImageView) convertView.findViewById(R.id.status_img);
				holder = new ViewHolder(name, statues);
				convertView.setTag(holder);
			}
			VpsData data = (VpsData) getItem(position);
			holder.name.setText(data.getName());
			if (Statues.SHUTDOWNING == data.getStatues())
			{
				holder.status.setImageResource(R.drawable.shutdowning);
			}
			else if (Statues.RESTARTING == data.getStatues())
			{
				holder.status.setImageResource(R.drawable.restart);
			}
			else if (Statues.STOPPED == data.getStatues())
			{
				holder.status.setImageResource(R.drawable.stopped);
			}
			else if (Statues.INSTALLING == data.getStatues())
			{
				holder.status.setImageResource(R.drawable.install_software);
			}
			else
			{
				holder.status.setImageResource(R.drawable.running);
			}
			return convertView;
		}

		private class ViewHolder
		{

			public ViewHolder(TextView name, ImageView status)
			{
				this.name = name;
				this.status = status;
			}

			TextView name;
			ImageView status;
		}
	}
}